package com.sweetsourfish.crm.activity.web;

import com.sweetsourfish.crm.activity.model.Activity;
import com.sweetsourfish.crm.activity.service.ActivityService;
import com.sweetsourfish.crm.commons.model.Constants;
import com.sweetsourfish.crm.commons.model.ResponseResult;
import com.sweetsourfish.crm.commons.utils.DateUtils;
import com.sweetsourfish.crm.commons.utils.UUIDUtils;
import com.sweetsourfish.crm.settings.model.User;
import com.sweetsourfish.crm.settings.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserService userService;

    //    workbench/index
    @RequestMapping("/index")
    public String workBeanchIndex(Model model) {

        /*获取  所有者集合*/
        List<User> users = userService.queryAll();
        model.addAttribute("users", users);
        return "/workbench/activity/index";
    }

    /*活动详情*/

    @RequestMapping("/detail")
    public String detail(String id,Model model){
        /*通过id获取 活动明细*/
        Activity activity = activityService.queryById(id);
        model.addAttribute("activity",activity);
        return "workbench/activity/detail";
    }

    @RequestMapping("/api/activityList")
    @ResponseBody
    public ResponseResult activityList(String name,
                                       String owner,
                                       String startDate,
                                       String endDate,
                                       Integer pageNum,
                                       Integer pageSize
    ) {

        System.out.println(name + owner);
        /*1 获取参数后 进行 处理*/
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        /*集合数据*/
        List<Activity> activities =
                activityService.queryPage(name, owner, startDate, endDate, pageNum, pageSize);
        /*页码*/
        /*总记录数*/
        int rows = activityService.queryListCount(name, owner, startDate, endDate);
        /*总页数*/
        int pages = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1;
        /*通过map 封装数据*/
        Map<String, Object> data = new HashMap<>();
        data.put("activities", activities);
        data.put("pageNum", pageNum);
        data.put("rows", rows);
        data.put("pages", pages);
        data.put("pageSize", pageSize);
        /*将 map 存入  result*/
        ResponseResult result = new ResponseResult(Constants.STATUS_OK, "成功", data);
        return result;
    }


    /*添加*/
    @RequestMapping(value = "/api/addActivity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult addActivity(Activity activity, HttpSession session) {
        ResponseResult result = new ResponseResult();

//        前端 传过来的 activity  缺少数据   id   createTime  createBy
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
        activity.setCreateBy(loginUser.getId());
        /*保存*/
        int rows = activityService.addActivity(activity);
        if (rows > 0) {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("添加成功");
        } else {
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("添加失败");
        }
        return result;
    }

    /*通过id 获取  活动信息*/
    @RequestMapping("/api/getActivity")
    @ResponseBody
    public ResponseResult queryById(String id) {
        ResponseResult result = new ResponseResult();

        Activity activity = activityService.queryById(id);
        if (activity != null) {
            result.setCode(Constants.STATUS_OK);
            result.setData(activity);
        } else {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("查无此数据");
            result.setData(activity);
        }
        return result;
    }


    /*更新*/

    @RequestMapping("/api/updateActivity")
    @ResponseBody
    public ResponseResult updateActivity(Activity activity, HttpSession session) {
        ResponseResult result = new ResponseResult();
        /*赋予 修改时间 和修改人*/
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
        activity.setEditBy(loginUser.getId());
        int rows = activityService.modifyActivity(activity);
        if (rows > 0) {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("修改成功");
        } else {
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("修改失败");
        }

        return result;
    }

    //删除
    @RequestMapping("/api/delete")
    @ResponseBody
    public ResponseResult deleteActivity(String[] ids) {
        ResponseResult result = new ResponseResult();
        //调用service层方法 删除活动
        try {
            int rows = activityService.deleteById(ids);
            if (rows > 0) {
                result.setCode(Constants.STATUS_OK);
            } else {
                result.setCode(Constants.STATUS_ERROR);
                result.setMsg("系统繁忙，请稍后重试...");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("系统繁忙，请稍后重试...");
        }

        return result;
    }

   /**
     * Description:  批量及选择性导出文件
     * @param ids 根据id进行导出
	 * @param response 响应
     * @return 导出结果
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(String[] ids, HttpServletResponse response) throws IOException {
        //获取数据
        List<Activity> activities = new ArrayList<>();
        if (ids!=null){
            //查ids
            activities = activityService.queryByIds(ids);
        }else {
            //查所有
            activities = activityService.queryAll();
        }

        //生产 POI的 DOM对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        HSSFSheet sheet = workbook.createSheet();

        //样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        //宽高
        sheet.setColumnWidth(0,30*256);
        sheet.setColumnWidth(1,30*256);
        sheet.setColumnWidth(2,30*256);
        sheet.setColumnWidth(3,30*256);
        sheet.setColumnWidth(4,150*256);

        //HSSFRow 行 第一行的表头
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cell = row0.createCell(0);
        cell.setCellValue("名称");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(1);
        cell.setCellValue("开始日期");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(2);
        cell.setCellValue("结束日期");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(3);
        cell.setCellValue("经费");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(4);
        cell.setCellValue("描述");
        cell.setCellStyle(cellStyle);

        //遍历 结果
        for (int i = 0; i <activities.size() ; i++) {
            HSSFRow row = sheet.createRow(i+1);
            cell = row.createCell(0);
            cell.setCellValue(activities.get(i).getName());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(1);
            cell.setCellValue(activities.get(i).getStartDate());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(2);
            cell.setCellValue(activities.get(i).getEndDate());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(3);
            cell.setCellValue(activities.get(i).getCost());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(4);
            cell.setCellValue(activities.get(i).getDescription());
            cell.setCellStyle(cellStyle);
        }
        //下载
        String finame = "市场活动"+DateUtils.formatDateTime(new Date())+".xls";
        //设置响应头
        response.setHeader("content-type","application/octet-stream");
        //文件名与编码
        response.setHeader("content-disposition","attachement;filename="+ URLEncoder.encode(finame,"UTF-8"));
        //直接 通过 response的流 写入
        workbook.write(response.getOutputStream());
        //刷新通道
        response.getOutputStream().flush();
    }

    /**
     * Description: 单独批量导出
     * @param response  请求
     * @return 是否可以下载成功
     */

   /* @RequestMapping("/exportExcel")
    public void exportAllActivitys(HttpServletResponse response) throws IOException {
        //调用service层方法 查询所有的市场活动
        List<Activity> activities = activityService.queryAll();
        //创建excel文件 并且activityList写入到excel文件中
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        HSSFRow row = sheet.createRow(0);//第一行 表头
        HSSFCell cell = row.createCell(0);//第一列
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("名称");
        cell = row.createCell(3);
        cell.setCellValue("开始日期");
        cell = row.createCell(4);
        cell.setCellValue("结束日期");
        cell = row.createCell(5);
        cell.setCellValue("成本");
        cell = row.createCell(6);
        cell.setCellValue("描述");
        cell = row.createCell(7);
        cell.setCellValue("创建时间");
        cell = row.createCell(8);
        cell.setCellValue("创建者");
        cell = row.createCell(9);
        cell.setCellValue("修改时间");
        cell = row.createCell(10);
        cell.setCellValue("修改者");

        //遍历activityList，创建HSSFRow对象，生成所有的数据行
        if(activities!=null && activities.size()>0){
            Activity activity=null;
            for(int i=0;i<activities.size();i++){
                activity=activities.get(i);

                //每遍历出一个activity，生成一行
                row=sheet.createRow(i+1);
                //每一行创建11列，每一列的数据从activity中获取
                cell=row.createCell(0);
                cell.setCellValue(activity.getId());
                cell=row.createCell(1);
                cell.setCellValue(activity.getOwner());
                cell=row.createCell(2);
                cell.setCellValue(activity.getName());
                cell=row.createCell(3);
                cell.setCellValue(activity.getStartDate());
                cell=row.createCell(4);
                cell.setCellValue(activity.getEndDate());
                cell=row.createCell(5);
                cell.setCellValue(activity.getCost());
                cell=row.createCell(6);
                cell.setCellValue(activity.getDescription());
                cell=row.createCell(7);
                cell.setCellValue(activity.getCreateTime());
                cell=row.createCell(8);
                cell.setCellValue(activity.getCreateBy());
                cell=row.createCell(9);
                cell.setCellValue(activity.getEditTime());
                cell=row.createCell(10);
                cell.setCellValue(activity.getEditBy());
            }
        }

        //代码过多
       *//* //根据wb对象生成excel文件
        OutputStream os = new FileOutputStream(new File("D:/activities.xls"));
        wb.write(os);
        os.close();
        wb.close();

        //把生成的excel文件下载到客户端
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=activities.xls");
        OutputStream out = response.getOutputStream();

        wb.write(out);
        wb.close();
        out.flush();*//*

        //下载
        String filename = "市场活动"+DateUtils.formatDateTime(new Date())+".xls";
        //设置响应头
        response.setHeader("content-type","application/octet-stream;charset=UTF-8");
        //文件名与编码
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
        //直接 通过 response的流 写入
        wb.write(response.getOutputStream());
        //刷新通道
        response.getOutputStream().flush();

    }

    *//**
     * Description: 单独选择下载
     * @param ids 根据id进行下载
	 * @param response  请求
     * @return 是否可以下载成功
     *//*

    @RequestMapping("/excel")
    public void excel(String[] ids ,HttpServletResponse response) throws IOException {
        //获取数据
        List<Activity> activities = new ArrayList<>();
        if(ids != null){
            //查ids
            activities = activityService.queryByIds(ids);

            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("市场活动列表");
            HSSFRow row = sheet.createRow(0);//第一行 表头
            HSSFCell cell = row.createCell(0);//第一列
            cell.setCellValue("ID");
            cell = row.createCell(1);
            cell.setCellValue("所有者");
            cell = row.createCell(2);
            cell.setCellValue("名称");
            cell = row.createCell(3);
            cell.setCellValue("开始日期");
            cell = row.createCell(4);
            cell.setCellValue("结束日期");
            cell = row.createCell(5);
            cell.setCellValue("成本");
            cell = row.createCell(6);
            cell.setCellValue("描述");
            cell = row.createCell(7);
            cell.setCellValue("创建时间");
            cell = row.createCell(8);
            cell.setCellValue("创建者");
            cell = row.createCell(9);
            cell.setCellValue("修改时间");
            cell = row.createCell(10);
            cell.setCellValue("修改者");


            //遍历activityList，创建HSSFRow对象，生成所有的数据行
            if(activities!=null && activities.size()>0){
                Activity activity=null;
                for(int i=0;i<activities.size();i++){
                    activity=activities.get(i);

                    //每遍历出一个activity，生成一行
                    row=sheet.createRow(i+1);
                    //每一行创建11列，每一列的数据从activity中获取
                    cell=row.createCell(0);
                    cell.setCellValue(activity.getId());
                    cell=row.createCell(1);
                    cell.setCellValue(activity.getOwner());
                    cell=row.createCell(2);
                    cell.setCellValue(activity.getName());
                    cell=row.createCell(3);
                    cell.setCellValue(activity.getStartDate());
                    cell=row.createCell(4);
                    cell.setCellValue(activity.getEndDate());
                    cell=row.createCell(5);
                    cell.setCellValue(activity.getCost());
                    cell=row.createCell(6);
                    cell.setCellValue(activity.getDescription());
                    cell=row.createCell(7);
                    cell.setCellValue(activity.getCreateTime());
                    cell=row.createCell(8);
                    cell.setCellValue(activity.getCreateBy());
                    cell=row.createCell(9);
                    cell.setCellValue(activity.getEditTime());
                    cell=row.createCell(10);
                    cell.setCellValue(activity.getEditBy());
                }

                //下载
                String finame = "市场活动"+DateUtils.formatDateTime(new Date())+".xls";
                //设置响应头
                response.setHeader("content-type","application/octet-stream");
                //文件名与编码
                response.setHeader("content-disposition","attachement;filename="+ URLEncoder.encode(finame,"UTF-8"));
                //直接 通过 response的流 写入
                wb.write(response.getOutputStream());
                //刷新通道
                response.getOutputStream().flush();
            }

        }
    }*/

    /*导入*/
    @RequestMapping(value = "/api/importExcel",method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult importExcel(MultipartFile activityFile,HttpSession session){
        ResponseResult result = new ResponseResult();
        try {
            //使用 MultipartFile 中 的输入流
            HSSFWorkbook workbook = new HSSFWorkbook(activityFile.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);
            //读取数据行
            List<Activity> activities = new ArrayList<>();
            //获取当前用户信息
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            for (int i = 1; i <=sheet.getLastRowNum() ; i++) {
                System.out.println(i);
                HSSFRow row = sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String startDate =  row.getCell(1).getStringCellValue();
                String endDate =  row.getCell(2).getStringCellValue();
                String cost =  row.getCell(3).getNumericCellValue()+"";
                String description = row.getCell(4).getStringCellValue();
                Activity activity = new Activity();
                activity.setName(name);
                activity.setStartDate(startDate);
                activity.setEndDate(endDate);
                activity.setCost(cost);
                activity.setDescription(description);

                activity.setId(UUIDUtils.getUUID());//主键
                activity.setOwner(user.getId());
                activity.setCreateBy(user.getId());
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activities.add(activity);
            }

            //保存到数据库
            int rows = activityService.saveActivityList(activities);
            System.out.println(rows);
            result.setCode(Constants.STATUS_OK);
            result.setMsg("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("导入异常");
        }
        return  result;
    }

}
